<?php

namespace app\api\controller;

use app\api\validate\AddressValidate;
use app\common\controller\Api;
use app\admin\model\UserAddress;
use baiduapi\AipNlp;
use fast\Tree;
use think\Cache;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 用戶地址管理
 */
class Address extends Api
{
    protected $noNeedLogin = ["area",'mapUrl','region'];
    protected $noNeedRight = ['*'];


    //地址列表
    public function list()
    {
        $keywords = $this->request->param('keywords');
        //設置過濾方法
        $this->request->filter(['strip_tags']);
        $user = $this->auth->getUser();
        $user_id = $user['id'];
        $type = $this->request->param("type",1);
        $type = $type==1?1:2;
        $model = new UserAddress();
        $list = $model
            ->where('user_id',$user_id)
            ->where('type',$type)
            ->order('is_default desc,id desc')
            ->paginate();
        $this->success('返回成功', $list);
    }

    //地址詳情
    public function show(){
        $userInfo = $this->auth->getUser();
        $request = $this->request;
        $user_id = $userInfo['id'];
        $id = (int)$request->param("id");
        $detail = Db::name("user_address")->where(['id'=>$id,'user_id'=>$user_id])->find();

        $this->success("ok",["detail"=>$detail?:""]);
    }

    //添加，編輯 --發貨地址
    public function detail()
    {
        $userInfo = $this->auth->getUser();
        $request = $this->request;
        $user_id = $userInfo['id'];

        $id = (int)$request->param("id",0);
        $addressModel = new UserAddress();
        if($id>0){
            $addressModel = $addressModel->where(['id'=>$id,'user_id'=>$user_id])->find();
            if(empty($addressModel)){
                $this->error("地址數據不存在");
            }
        }
        $username = $request->post("username",'');
        $area_code = $request->post("area_code",'');
        $mobile = $request->post("mobile");
        $country = "中國";
        $province_id = (int)$request->post("province_id");
        $city_id = (int)$request->post("city_id");
        $district_id = (int)$request->post("district_id");
        $address = $request->post("address",'');
        $zip_code = $request->post("zip_code",'');
        $email = $request->post("email",'');
        $id_code = $request->post("id_code",'');
        $id_z_image = $request->post("id_z_image",'');
        $id_f_image = $request->post("id_f_image",'');
        $type = (int)$request->post("type"); //1发件人，2收件人
        $type = $type==1?1:2;
        if(empty($username)){
            $this->error("請填寫用戶名");
        }
        if(empty($area_code)){
        //    $this->error("請填寫手機區號");
        }
        if(empty($mobile)){
            $this->error("請填寫手機號");
        }
        if(!isMobile($mobile)){
            $this->error("手機號格式不正確");
        }
        if($type==2){
            if($province_id<1 || $city_id<1 || $district_id<1){
             //   $this->error("請選擇地區");
            }
            $provinceInfo = Db::name("area")->where(['id'=>$province_id])->find();
            if(empty($provinceInfo)){
            //    $this->error("地區1不存在");
            }
            $cityInfo = Db::name("area")->where(['id'=>$city_id])->find();
            if(empty($cityInfo)){
            //    $this->error("地區2不存在");
            }
            $districtInfo = Db::name("area")->where(['id'=>$district_id])->find();
            if(empty($districtInfo)){
            //    $this->error("地區3不存在");
            }
        }



        if(empty($address)){
            $this->error("請填寫詳細地址");
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }

        $is_default = (int)$request->post('is_default',0);
        $is_default = $is_default==1?1:0;
        $data = [
            'user_id'=>$user_id,
            'username'=>$username,
            'mobile'=>$mobile,
            'area_code'=>"",
            'country'=>$country,
            'province_id'=>$province_id,
            'province'=>$provinceInfo['name']??'',
            'city_id'=>$city_id,
            'city'=>$cityInfo['name']??'',
            'district_id'=>$district_id,
            'district'=>$districtInfo['name']??'',
            'address'=>$address,
            'zip_code'=>$zip_code,
            'is_default'=>$is_default,
            'type'=>$type,
            'email'=>$email,
            'id_code'=>$id_code,
            'id_z_image'=>$id_z_image,
            'id_f_image'=>$id_f_image
        ];


        $default_check = Db::name("user_address")->where(['user_id'=>$user_id,'is_default'=>1,'type'=>$type])->count();
        if($default_check == 0){
            $data['is_default'] = 1;
        }
        Db::startTrans();
        try{
            if($is_default == 1 && $default_check>0){
                Db::name("user_address")->where(['user_id'=>$user_id,'is_default'=>1,'type'=>$type])->update(['is_default'=>0]);
            }
            $res = $addressModel->allowField(true)->save($data);
            if (!$res) {
                throw new Exception(__("Operation failed"));
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success(__("Operation completed"));
    }



    //獲取默認地址
    public function defaultAddress(){
        $user_id = $this->auth->id;
        $info = Db::name("user_address")
            ->where(['is_default'=>1,'user_id'=>$user_id])
            ->find();

        $this->success('ok',$info?:"");
    }

    //刪除用戶地址
    public function del()
    {
        $id = (int)$this->request->param("id");
        if($id < 1){
            $this->error("缺少參數");
        }
        $userInfo = $this->auth->getUser();
        $user_id = $userInfo['id'];
        $model = new UserAddress();
        $info = $model->where(['id' =>$id,'user_id'=>$user_id])->find();
        if(empty($info)) {
            $this->error(__("Operation failed"));
        }
        $res = $info->delete();
        if (!$res) {
            $this->error(__("Operation failed"));
        }
        $this->success(__("Operation completed"));
    }

    //獲取地區
    public function area()
    {
        $tree    = Tree::instance();
        $areaList = Cache::get('post_region', '');
        $areaList = "";
        if(empty($areaList)){
            $areaArr = [];
            $list = Db::name("area")->field(["id","pid","name"])->select();
            $pid_ar=[0];
            while (true){
                $num = count($areaArr);
                foreach ($list as $k=>$area) {
                    if(in_array($area['pid'],$pid_ar)){
                        $areaArr[$area['id']] = [
                            'id' => $area['id'],
                            'pid' => $area['pid'],
                            'text' => $area['name'],
                        ];
                        $pid_ar[] = $area['id'];
                        unset($list[$k]);
                    }
                }
                if(count($areaArr) == $num){
                    break;
                }
            }
            $areaList = [];
            foreach ($areaArr as $k=>$val){
                if(isset($areaArr[$val['pid']])){
                    $areaArr[$val['pid']]["children"][] = &$areaArr[$k];
                }else{
                    $areaList[] = &$areaArr[$k];
                }
            }
            Cache::set('post_region', $areaList);
        }

        $this->success('ok', $areaList);
    }


    public function mapUrl(){
        $key = "AIzaSyACo7peBWekTLEpWrTzCSgj9mzvuTims4Y";
        //http://114.xixik.com/country-code/#anchor1    國家地區代碼表
        $country = 'HK'; //香港
        //https://developers.google.com/maps/documentation/geocoding/requests-geocoding   地址反編碼
        $url = "https://maps.googleapis.com/maps/api/geocode/json?components=country:$country&key=$key&address=";

        $this->success('ok',['url'=>$url]);
    }

    //地區
    public function region(){
        $list = Db::name("area")->where(['level'=>3])->where("pid",">",3716)->field(['id','name'])->select();
        $this->success("ok",['list'=>$list]);
    }


    // 智能识别收货地址
    public function autoAddress(){
        $address = $this->request->post('address');
        if(!$address){
            $this->error(__('Please enter address'));
        }
        $detail = [];
        try {
            $detail = \fast\Address::smart_parse($address);
        }catch (Exception $e){
            $this->error('识别未获取到信息');
        }

        $this->success('ok',$detail);
    }

    //百度api接口地址纠错
    public function actionBaiduApi(){
        $app_id = '23175914';
        $api_key = 'hvzfnKz0ezMmmwcFSSE0n6a9';
        $secret_key = 'aSQMc41mTGd0sOOyOTTYgqD2VTMFkqp0';
        $client =  new AipNlp($app_id,$api_key,$secret_key);
        $text = "河南 郑州 中原区 北林路 政七街";
        $text = "收货人: 陈先生手机号码: 13306956707所在地区: 福建省漳州市龙文区详细地址: 九龙大道万达广场小区c区1号楼2单元905室";
        // 调用地址识别接口
        $data = $client->address($text);
        p($data);die;
    }

}
